package com.yuanluludev.lib_webview.web

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import com.yuanluludev.lib_webview.R
import kotlinx.android.synthetic.main.fragment_web.rlContainer
import kotlinx.android.synthetic.main.fragment_web.titleBar

/**
 * yuanLulu
 * 用于在fragment中加载web页面
 */
class WebFragment : BaseAgentWebFragment() {

    private var webTitle: String = ""

    companion object {
        private const val WEB_URL = "web_url"
        private const val WEB_TITLE = "web_title"
        private const val IS_SHOW_TITLE_BAR = "is_show_title_bar"
        fun newInstance(webUrl: String, webTitle: String="", isShowTitleBar: Boolean = true) =
            WebFragment().apply {
                arguments = Bundle().apply {
                    putString(WEB_URL, webUrl)
                    putString(WEB_TITLE, webTitle)
                    putBoolean(IS_SHOW_TITLE_BAR, isShowTitleBar)
                }
            }
    }

    override fun getLayoutResId() = R.layout.fragment_web

    override fun getAgentWebParent(): ViewGroup = rlContainer

    override fun initEvents() {
        val isShowTitleBar = arguments?.getBoolean(IS_SHOW_TITLE_BAR, true) ?: true
        titleBar?.visibility = if (isShowTitleBar) View.VISIBLE else View.GONE

        webTitle = arguments?.getString(WEB_TITLE) ?: ""
        if (!TextUtils.isEmpty(webTitle)) titleBar?.setTitleText(webTitle)
    }

    override fun getUrl(): String {
        return arguments?.getString(WEB_URL) ?: ""
    }

    override fun setTitle(view: WebView?, title: String?) {
        if (!TextUtils.isEmpty(webTitle)) return
        if (!TextUtils.isEmpty(title)) {
            titleBar?.setTitleText(title)
        }
    }

}